﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SmartForm.NetJs
{
    [ComVisibleAttribute(true)]
    public class IEJs
    {
        Form mainWindow;
        WebBrowser ieWebBrowser;

        public IEJs(Form main)
        {
            mainWindow = main;
        }


        #region 执行JS
        /// <summary>
        /// 执行js并且访问成功才能执行下一步
        /// </summary>
        /// <param name="jsStr"></param>
        public void ExeScript(string jsStr)
        {
            string funcName = "_" + Guid.NewGuid().ToString("N");
            HtmlElement element2 = ieWebBrowser.Document.CreateElement("script");
            element2.SetAttribute("type", "text/javascript");
            element2.SetAttribute("text", "function " + funcName + "(){ " + jsStr + " }");   //这里写JS代码
            HtmlElement head = ieWebBrowser.Document.Body.AppendChild(element2);
            bool isOk = (bool)ieWebBrowser.Document.InvokeScript(funcName);
            Console.Write("返回状态" + isOk.ToString());
            if (!isOk)
            {
                //执行js未成功，1秒后重试
                Delay(1);
                ExeScript(jsStr);
            }
        }

        /// <summary>
        /// 使用eval执行任意脚本。注意：eval在局部作用域中执行，而execScript在全局作用域中执行。
        /// </summary>
        public object ExeScriptResult(string script)
        {
            Console.Write(ieWebBrowser.Document.ToString());
            var document = ieWebBrowser.Document;
            if (document == null) return null;
            var result = document.InvokeScript("eval", new object[] { script });
            return result;
        }

        /// <summary>
        /// 延迟系统时间，但系统又能同时能执行其它任务
        /// </summary>
        /// <param name="second"></param>
        public void Delay(int second)
        {
            DateTime current = DateTime.Now;
            while (current.AddSeconds(second) > DateTime.Now)
            {
                Application.DoEvents();//转让控制权            
            }
            return;
        }
        #endregion


        //JS调WinForm方法的接口
        public void HtmlCmd(string cmd)
        {
            MessageBox.Show(cmd);
        }
    }
}
